package com.lianzai.wxapp.service.impl;

import com.lianzai.mobile.dao.WxUserDao;
import com.lianzai.mobile.domain.WxUserDO;
import com.lianzai.user.dao.BusinessLicenseDao;
import com.lianzai.user.dao.UserInfoDao;
import com.lianzai.user.domain.UserInfoDO;
import com.lianzai.wxapp.domain.ResidentRegisterInfo;
import com.lianzai.wxapp.service.ResidentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class ResidentServiceImpl implements ResidentService {

    @Autowired
    private WxUserDao wxUserDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private BusinessLicenseDao licenseDao;

    @Override
    @Transactional
    public int saveResident(ResidentRegisterInfo registerInfo) {

        //新增业务用户信息
        UserInfoDO user = new UserInfoDO();
        user.setMobile(registerInfo.getMobilePhone());
        user.setAddr(registerInfo.getAddress());
        user.setName(registerInfo.getName());
        user.setRole(1);
        user.setAuditStatus(1);  //普通用户注册时自动通过审核，后续注册车辆时要审核
        int ret = userInfoDao.save(user);

        if (ret == 0)
        {
            return 0;
        }

        //新增微信用户信息
        WxUserDO wxUser = new WxUserDO();
        wxUser.setOpenId(registerInfo.getOpenId());
        wxUser.setUserId(user.getId());

        try {
            ret = wxUserDao.save(wxUser);
            if (ret == 0) {
                //手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }

        return ret;
    }

    @Override
    @Transactional
    public int updateResident(ResidentRegisterInfo registerInfo) {

        //新增业务用户信息
        UserInfoDO user = new UserInfoDO();
        user.setId(registerInfo.getUserId());
        user.setMobile(registerInfo.getMobilePhone());
        user.setAddr(registerInfo.getAddress());
        user.setName(registerInfo.getName());
        user.setAuditStatus(0);
        int ret = userInfoDao.update(user);

        if (ret == 0)
        {
            return 0;
        }

        return ret;
    }

}
